// 注册页面逻辑 - 中医适宜技术防控青少年近视系统

const { register, sendSmsCode } = require('../../utils/auth.js');

Page({
  data: {
    // 表单数据
    formData: {
      phone: '',
      code: '',
      password: '',
      confirmPassword: '',
      realName: ''
    },
    
    // 表单验证错误
    errors: {
      phone: '',
      code: '',
      password: '',
      confirmPassword: '',
      realName: ''
    },
    
    // 密码显示控制
    showPassword: false,
    showConfirmPassword: false,
    
    // 验证码倒计时
    countdown: 0,
    codeLoading: false,
    
    // 注册状态
    registerLoading: false,
    
    // 协议同意
    agreed: false,
    
    // 弹窗控制
    showUserAgreementModal: false,
    showPrivacyPolicyModal: false
  },

  /**
   * 页面加载
   */
  onLoad() {
    console.log('注册页面加载');
  },

  /**
   * 页面卸载时清理定时器
   */
  onUnload() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },

  /**
   * 手机号输入
   */
  onPhoneInput(e) {
    const phone = e.detail.value;
    this.setData({
      'formData.phone': phone,
      'errors.phone': ''
    });
  },

  /**
   * 验证码输入
   */
  onCodeInput(e) {
    const code = e.detail.value;
    this.setData({
      'formData.code': code,
      'errors.code': ''
    });
  },

  /**
   * 密码输入
   */
  onPasswordInput(e) {
    const password = e.detail.value;
    this.setData({
      'formData.password': password,
      'errors.password': '',
      'errors.confirmPassword': '' // 密码变化时清除确认密码错误
    });
  },

  /**
   * 确认密码输入
   */
  onConfirmPasswordInput(e) {
    const confirmPassword = e.detail.value;
    this.setData({
      'formData.confirmPassword': confirmPassword,
      'errors.confirmPassword': ''
    });
  },

  /**
   * 真实姓名输入
   */
  onRealNameInput(e) {
    const realName = e.detail.value;
    this.setData({
      'formData.realName': realName,
      'errors.realName': ''
    });
  },

  /**
   * 切换密码显示
   */
  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  /**
   * 切换确认密码显示
   */
  toggleConfirmPassword() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    });
  },

  /**
   * 验证手机号
   */
  validatePhone(phone) {
    if (!phone) {
      return '请输入手机号';
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return '请输入正确的手机号';
    }
    return '';
  },

  /**
   * 发送验证码
   */
  async sendCode() {
    const { phone } = this.data.formData;
    
    // 验证手机号
    const phoneError = this.validatePhone(phone);
    if (phoneError) {
      this.setData({ 'errors.phone': phoneError });
      wx.showToast({
        title: phoneError,
        icon: 'error'
      });
      return;
    }

    try {
      this.setData({ codeLoading: true });

      // 调用发送验证码接口
      const result = await sendSmsCode(phone, 'register');
      
      if (result.success) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
        
        // 开始倒计时
        this.startCountdown();
      } else {
        wx.showToast({
          title: result.message || '发送失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      wx.showToast({
        title: error.message || '发送失败',
        icon: 'error'
      });
    } finally {
      this.setData({ codeLoading: false });
    }
  },

  /**
   * 开始倒计时
   */
  startCountdown() {
    let countdown = 60;
    this.setData({ countdown });
    
    this.countdownTimer = setInterval(() => {
      countdown--;
      this.setData({ countdown });
      
      if (countdown <= 0) {
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
      }
    }, 1000);
  },

  /**
   * 表单验证
   */
  validateForm() {
    const { phone, code, password, confirmPassword, realName } = this.data.formData;
    const errors = {};
    let isValid = true;

    // 验证手机号
    const phoneError = this.validatePhone(phone);
    if (phoneError) {
      errors.phone = phoneError;
      isValid = false;
    }

    // 验证验证码
    if (!code) {
      errors.code = '请输入验证码';
      isValid = false;
    } else if (!/^\d{4}$/.test(code)) {
      errors.code = '验证码格式不正确';
      isValid = false;
    }

    // 验证密码
    if (!password) {
      errors.password = '请输入密码';
      isValid = false;
    } else if (password.length < 6) {
      errors.password = '密码至少6位';
      isValid = false;
    } else if (password.length > 20) {
      errors.password = '密码最多20位';
      isValid = false;
    }

    // 验证确认密码
    if (!confirmPassword) {
      errors.confirmPassword = '请确认密码';
      isValid = false;
    } else if (password !== confirmPassword) {
      errors.confirmPassword = '两次密码不一致';
      isValid = false;
    }

    // 验证真实姓名
    if (!realName) {
      errors.realName = '请输入真实姓名';
      isValid = false;
    } else if (realName.length < 2) {
      errors.realName = '姓名至少2个字符';
      isValid = false;
    }

    this.setData({ errors });
    return isValid;
  },

  /**
   * 切换协议同意状态
   */
  toggleAgreement() {
    this.setData({
      agreed: !this.data.agreed
    });
  },

  /**
   * 显示用户协议
   */
  showUserAgreement() {
    this.setData({
      showUserAgreementModal: true
    });
  },

  /**
   * 关闭用户协议
   */
  closeUserAgreement() {
    this.setData({
      showUserAgreementModal: false
    });
  },

  /**
   * 显示隐私政策
   */
  showPrivacyPolicy() {
    this.setData({
      showPrivacyPolicyModal: true
    });
  },

  /**
   * 关闭隐私政策
   */
  closePrivacyPolicy() {
    this.setData({
      showPrivacyPolicyModal: false
    });
  },

  /**
   * 处理注册
   */
  handleRegister() {
    if (this.data.registerLoading) return;

    // 检查协议同意
    if (!this.data.agreed) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'error'
      });
      return;
    }

    // 表单验证
    if (!this.validateForm()) {
      // 显示第一个错误信息
      const { errors } = this.data;
      const firstError = errors.phone || errors.code || errors.password || errors.confirmPassword || errors.realName;
      if (firstError) {
        wx.showToast({
          title: firstError,
          icon: 'error'
        });
      }
      return;
    }

    this.setData({ registerLoading: true });

    const { phone, code, password, realName } = this.data.formData;
    
    register({
      phone,
      code,
      password,
      realName
    })
    .then((result) => {
      this.setData({ registerLoading: false });
      
      if (result.success) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });

        // 保存用户信息
        wx.setStorageSync('userInfo', result.userInfo);
        
        // 注册成功后跳转
        setTimeout(() => {
          wx.showModal({
            title: '注册成功',
            content: '是否立即绑定学生信息？',
            confirmText: '立即绑定',
            cancelText: '稍后再说',
            success: (res) => {
              if (res.confirm) {
                // 跳转到学生绑定页面
                wx.redirectTo({
                  url: '/pages/bind/bind'
                });
              } else {
                // 跳转到首页
                wx.switchTab({
                  url: '/pages/index/index'
                });
              }
            }
          });
        }, 1500);
      } else {
        wx.showToast({
          title: result.message || '注册失败',
          icon: 'error'
        });
      }
    })
    .catch((error) => {
      this.setData({ registerLoading: false });
      console.error('注册失败:', error);
      wx.showToast({
        title: error.message || '注册失败',
        icon: 'error'
      });
    });
  },

  /**
   * 跳转到登录页面
   */
  navigateToLogin() {
    wx.navigateBack();
  },

  /**
   * 分享功能
   */
  onShareAppMessage() {
    return {
      title: '中医适宜技术防控青少年近视系统',
      path: '/pages/welcome/welcome'
    };
  }
});
